<template>
  <div
    class="chart-box"
    ref="chartBox"
    v-bind:style="{
      width: typeof width === 'string' ? width : width + 'px',
      height: typeof height === 'string' ? height : height + 'px'
    }"
  >
    <div class="chart-wrapper" ref="chart"></div>
  </div>
</template>

<script>
import * as echarts from "echarts";
export default {
  name: "chartTemplate",
  props: {
    width: {
      type: [Number, String],
      default: "100%",
    },
    height: {
      type: [Number, String],
      default: "100%",
    },
    option: {
      type: Object,
      default: () => {
        return {
        };
      },
    },
  },
  data() {
    return {
      _myChart: null,
      chart: null,
      chartBox: null,
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initEchart();
    });
  },
  methods: {
    initEchart() {
      if (this._myChart) this._myChart.clear();
      !this._myChart && (this._myChart = echarts.init(this.$refs.chart));
      this._myChart.setOption(this.option);
      window.addEventListener("resize", () => {
        this._myChart.resize();
      });
      
    },
  },
  watch: {
    option: {
      handler(value) {
        this._myChart && this._myChart.clear();
        this._myChart.setOption(value);
      },
      deep: true,
    },
  },
  destroyed() {
    this._myChart && this._myChart.dispose();
  },
  components: {},
};
</script>

<style scoped lang='scss'>
.chart-box {
  //   opacity: 0;
//   margin: 0 auto;
  .chart-wrapper {
    width: 100%;
    height: 100%;
  }
}
</style>